﻿using MeetAI.Utility;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MeetAI.Repository
{
    public class DbFactory
    {
        /// <summary>
        /// SqlSugarClient属性
        /// </summary>
        /// <returns></returns>
        public static SqlSugarClient GetSqlSugarClient()
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = ConfigurationManager.AppSettings["masterDB"].ToString(), //必填
                DbType = DbType.MySql, //必填
                IsAutoCloseConnection = true, //默认false
                InitKeyType = InitKeyType.Attribute
            }); //默认SystemTable

            //#if Debug

            db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
            {

            };
            db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
            {
                Log.Debug("执行 SQL 语句 如下:" + sql);
                if (pars != null)
                {
                    Log.Debug(" 提交参数 :" + JsonConvert.SerializeObject(pars.ToDictionary(s => s.ParameterName, s => s.Value)));
                }
            };
            db.Aop.OnError = (exp) =>//执行SQL 错误事件
            {
                //exp.sql exp.parameters 可以拿到参数和错误Sql             
            };
            db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL执行前 可以修改SQL
            {
                return new KeyValuePair<string, SugarParameter[]>(sql, pars);
            };
            //#endif

            return db;
        }
    }
}
